<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="标题" prop="name">
            <el-input v-model="formItem.name" placeholder="请输入标题" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配置项" required>
            <el-input v-model="formItem.objName" placeholder="请选择配置项" @focus="handleSelectInstances" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人" prop="applyUserName">
            <el-input v-model="formItem.applyUserName" placeholder="请输入标题" :maxlength="255" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="事件来源" prop="incidentFrom">
            <el-select v-model="formItem.incidentFrom" class="select_input" placeholder="事件来源">
              <el-option v-for="(item) in incidentFroms" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请方式" prop="communicationNumber">
            <div>
              <el-input
                v-model="formItem.communicationNumber"
                placeholder="请输入内容"
              >
                <el-select slot="prepend" v-model="formItem.applyTypeName" style="width: 80px;" placeholder="请选择">
                  <el-option v-for="item in applyTypes" :key="item.value" :label="item.text" :value="item.value" @click.native="changeType(item)" />                </el-select>
              </el-input>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请时间" prop="applyTime">
            <el-date-picker
              v-model="formItem.applyTime"
              type="date"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="影响范围" prop="coverageInfluence">
            <el-select v-model="formItem.coverageInfluence" class="select_input" placeholder="影响范围" @change="selectChange">
              <el-option v-for="(item) in coverageInfluences" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="紧急程度" prop="urgency">
            <el-select v-model="formItem.urgency" class="select_input" placeholder="紧急程度" @change="selectChange">
              <el-option v-for="(item) in urgencys" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="formItem.priority" class="select_input" placeholder="优先级">
              <el-option v-for="(item) in prioritys" :key="item.priority" :label="item.priorityName" :value="item.priority" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="执行人" prop="dispatchUserName">
            <el-input v-model="formItem.dispatchUserName" placeholder="请选择执行人" @focus="handleUserIconClick" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="附件">
            <el-upload
              class="upload-demo"
              :headers="headers"
              :action="importUrl"
              :file-list="formItem.attachments"
              :before-upload="handleBeforeUpLoad"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="详细说明" prop="description">
            <!-- <Tinymce ref="tinymce" v-model="formItem.description" :height="260" menubar="false" /> -->
            <el-input v-model="formItem.description" placeholder="请输入" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :offset="20" :span="4">
          <el-button size="mini" type="warning" @click="ok('temporary')">暂存</el-button>
          <el-button size="mini" type="primary" @click="ok('submit')">提交</el-button>
        </el-col>
      </el-row>
    </el-form>
    <SelectDialog v-if="userSelDialogFormVisible" title="选择分发人" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" :org-code="formItem.orgCode" />
    </SelectDialog>
    <SelectDialog v-if="instanceSelDialogFormVisible" title="选择维护对象" width="90%" :append-to-body="true" :show="instanceSelDialogFormVisible" @on-ok="selectInstanceOk" @on-cancel="selectInstanceCancel">
      <instancesTable ref="instancesTable" :for-selection="true" />
    </SelectDialog>
  </div>
</template>

<script>
import {
  create,
  detail,
  importUrl,
  deleteAttachmentByFsId
} from '@neu/dcom-ui/api/incidentRegister'
import { getByParams } from '@neu/dcom-ui/api/priority'
// import Tinymce from '@neu/biz-core/components/Tinymce'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import UsersPage from '@neu/auth-ui/views/users/tables'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
// import instancesTable from '@neu/dcom-ui/views/instancesFromModel/tables'
import instancesTable from '@neu/dcam-ui/views/fixedAsset'
import { getToken } from '@neu/biz-core/utils/auth'

const formItem = {
  name: '',
  objCode: null,
  objName: '',
  objId: '',
  applyUserCode: '',
  applyUserName: '',
  dispatchUserCode: '',
  dispatchUserName: '',
  applyTypeName: '',
  applyType: '',
  communicationNumber: '',
  applyTime: '',
  coverageInfluence: '',
  urgency: '',
  priority: '',
  incidentFrom: '',
  description: '',
  executeUserCode: '',
  executeUserName: '',
  status: 'temporary',
  // 附件列表
  attachments: []
}
export default {
  name: 'IncidentEditForm',
  components: {
    // Tinymce,
    UsersPage,
    SelectDialog,
    instancesTable
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      /** 上传路径 */
      importUrl: importUrl,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      /** 配置项dialog */
      instanceSelDialogFormVisible: false,
      /** 优先级 */
      prioritys: [],
      /** 事件来源 */
      incidentFroms: [],
      /** 申请方式 */
      applyTypes: [],
      /** 影响范围 */
      coverageInfluences: [],
      /** 紧急程度 */
      urgencys: [],
      /** 是否显示用户选择对话框 */
      userSelDialogFormVisible: false,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '标题不能为空',
          trigger: 'blur'
        }],
        modelCode: [{
          required: true,
          message: '配置项不能为空',
          trigger: 'change  '
        }],
        applyUserName: [{
          required: true,
          message: '申请人不能为空',
          trigger: 'change  '
        }],
        dispatchUserName: [{
          required: true,
          message: '分发人不能为空',
          trigger: 'change  '
        }],
        applyType: [{
          required: true,
          message: '申请方式不能为空',
          trigger: 'change'
        }],
        communicationNumber: [{
          required: true,
          message: '通讯号码不能为空',
          trigger: 'blur'
        }],
        applyTime: [{
          required: true,
          message: '申请不能为空',
          trigger: 'change'
        }],
        coverageInfluence: [{
          required: true,
          message: '影响范围不能为空',
          trigger: 'change'
        }],
        urgency: [{
          required: true,
          message: '紧急程度不能为空',
          trigger: 'change'
        }],
        priority: [{
          required: true,
          message: '优先级不能为空',
          trigger: 'change'
        }],
        incidentFrom: [{
          required: true,
          message: '事件来源不能为空',
          trigger: 'change'
        }],
        description: [{
          required: true,
          message: '详细说明不能为空',
          trigger: 'blur'
        }]
      }
    }
  },
  watch: {

  },
  created() {
    this.fetch()
    findByDictionaryType('coverageInfluence').then(response => {
      this.coverageInfluences = response.data
    })
    findByDictionaryType('urgency').then(response => {
      this.urgencys = response.data
    })
    findByDictionaryType('applyType').then(response => {
      this.applyTypes = response.data
    })
    findByDictionaryType('incidentFrom').then(response => {
      this.incidentFroms = response.data
    })
  },
  methods: {
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    ok(value) {
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (this.formItem.applyType === 'telephone') {
              if (!(/^1[34578]\d{9}$/.test(this.formItem.communicationNumber))) {
                return this.$message({
                  showClose: true,
                  message: '电话号码不合法',
                  type: 'error'
                })
              }
            }
            if (this.formItem.applyType === 'mail') {
              var reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
              if (!(reg.test(this.formItem.communicationNumber))) {
                return this.$message({
                  showClose: true,
                  message: '邮件地址不合法',
                  type: 'error'
                })
              }
            }
            this.formItem.executeUserCode = this.formItem.dispatchUserCode
            this.formItem.executeUserName = this.formItem.dispatchUserName
            if (value === null) {
              this.formItem.status = 'temporary'
            } else {
              this.formItem.status = value
            }
            create(this.formItem).then(res => {
              if (res.status === 'success') {
                this.$emit('cancelNewOrderForm', 'refresh')
              }
            })
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
      this.formItem = { ...formItem }
    },
    selModel(node) {
      this.formItem.objName = node.name
    },
    /** 选择用户按钮 */
    handleUserIconClick() {
      this.userSelDialogFormVisible = true
    },
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个负责人',
          type: 'error'
        })
      }
      if (users.length < 1) {
        this.formItem.dispatchUserCode = ''
        this.formItem.dispatchUserName = ''
      } else {
        this.formItem.dispatchUserName = users[0].name ? users[0].name : users[0].username
        this.formItem.dispatchUserCode = users[0].username
      }
      this.userSelDialogFormVisible = false
    },
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    changeType(item) {
      this.formItem.applyTypeName = item.text
      this.formItem.applyType = item.code
    },
    selectInstanceOk() {
      const instances = this.$refs.instancesTable.selections
      if (instances.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个配置项',
          type: 'error'
        })
      }
      if (instances.length < 1) {
        this.formItem.objCode = ''
        this.formItem.objName = ''
        this.formItem.objId = ''
      } else {
        this.formItem.objName = instances[0].name
        this.formItem.objCode = instances[0].code
        this.formItem.objId = instances[0].id
      }
      this.instanceSelDialogFormVisible = false
    },
    selectInstanceCancel() {
      this.instanceSelDialogFormVisible = false
    },
    /** 选择对象 */
    handleSelectInstances() {
      this.instanceSelDialogFormVisible = true
    },
    selectChange() {
      if (this.formItem.coverageInfluence !== '' && this.formItem.urgency !== '') {
        getByParams(this.formItem.coverageInfluence, this.formItem.urgency).then(response => {
          this.prioritys = response.data
        })
      }
    },
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachments.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachments.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    handleError(err, file, fileList) {
      console.log(err)
    },
    handleRemove(file, fileList) {
      deleteAttachmentByFsId(file.fsId).then(res => {
        if (res.status === 'failure') {
          this.$message({
            showClose: true,
            message: res.data,
            type: 'error'
          })
        } else {
          this.formItem.attachments.splice(this.formItem.attachments.indexOf(file), 1)
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        }
      })
    },
    handleBeforeUpLoad(file) {

    }
  }
}
</script>
